package com.bop.dehong.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.LogUtils;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.base.ActManager;
import com.bop.dehong.config.Config;
import com.bop.dehong.http.model.UpdateApkModel;
import com.bop.dehong.info.entity.VersionEntity;
import com.bop.dehong.widget.dialog.Effectstype;
import com.bop.dehong.widget.dialog.NiftyDialogBuilder;


/**
 * @describe:TODO 自动更新 <br/>
 *                使用方法: 外部只需要调用update()方法，传入该应用已经分配好的key(key由应用在服务端注册时，由服务端生成给出)
 * @author: mayday
 * @date:2013-2-2
 */
@SuppressLint("HandlerLeak")
public class UpdateManager {
	/* 界面更新处理的分类 */
	private static final int CREATE_DIALOG = 4;// 提示更新对话框
	private static final int SHOWTOASH = 5;
	private Activity mActivity;
	/* 请求服务端是否有更新时得到的版本信息 */
	private UpdateAPKItem mUpdateAPKItem;
	private boolean mShowNewest = false;
	private Long local;
	
	/**
	 * 下载界面更新
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case CREATE_DIALOG:
				getUpdate(mActivity);
				break;
			case SHOWTOASH:
				ToastUtils.showLong(mActivity, "应用已经是最新版");
				break;
			}
		}
	};
	
	
	/**
	 * @param activity
	 *            构造函数
	 */
	public UpdateManager(Activity activity) {
		this.mActivity = activity;
	}

	/**
	 * 开始检查更新
	 */
	public UpdateManager update(final String updateKey) {
		checkUpdate(updateKey);
		return this;
	}

	/**
	 * 是否显示最新版本提示信息
	 * 
	 * @param show
	 */
	public void showNewestVersionToast(boolean show) {
		mShowNewest = show;
	}

	
	private UpdateApkModel updateapkmodel;
	
	/**
	 * @describe:TODO 检查更新
	 * @param context
	 * @param checkUpdateUrl
	 *            检查更新的服务器地址
	 * @return
	 */
	@SuppressWarnings("unused")
	private void checkUpdate(String updateKey) {
		if (updateapkmodel == null) {
			if (updateapkmodel == null) {
				updateapkmodel = new UpdateApkModel(mActivity, callback);
			}
			local = System.currentTimeMillis() / 1000;
			updateapkmodel.doNet();
		}		
	}

	RequestCallBack<VersionEntity> callback = new RequestCallBack<VersionEntity>() {

		@Override
		public void end() {
		}
		
		public void onSuccess(VersionEntity info) {
			Long net = info.getStamp();
			Long modify = net - local;
			if (Math.abs(modify) >= 300) {
				PreferencesUtils.putLong(mActivity, Config.TAG, modify);	
			}
			mUpdateAPKItem = info.getVersion();
			if (mUpdateAPKItem != null) {
				int version = getVersionCode();
				if (mUpdateAPKItem.getVersion_code() != null) {
					if (Integer.valueOf(mUpdateAPKItem.getVersion_code()) > version) {
						handler.sendEmptyMessage(CREATE_DIALOG);
					} else {
						if (mShowNewest) {
							handler.sendEmptyMessage(SHOWTOASH);
						}
					}
				}
			}
			super.onSuccess(info);
		};
		
	};

	/**
	 * 更新对话框
	 */
	private void getUpdate(Activity activity) {
		final NiftyDialogBuilder builder = NiftyDialogBuilder
				.getInstance(activity);
		builder.withTitle("应用程序有新版本更新");
		StringBuilder sb = new StringBuilder();
		sb.append("最新版本:").append(mUpdateAPKItem.getVersion_name())
				.append("\n").append(mUpdateAPKItem.getUpdate_log());
		builder.withMessage(sb);
		builder.withDuration(300);
		builder.withEffect(Effectstype.RotateBottom);
		builder.isCancelableOnTouchOutside(false);
		builder.isCancelable(false);
		builder.withButtonLeftText("立即更新");
		builder.withButtonRightText("以后再说");
		builder.setButtonLeftClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.dismiss();
				intoDownloadManager(mActivity);
				if (Integer.valueOf(mUpdateAPKItem.getIs_force()) == UpdateAPKItem.UPDATE_IS_FORCE){
					ActManager.getAppManager().finishAllActivity();
				}
			}
		});
		builder.setButtonRightClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.dismiss();
				// 判断是否属于需要强制更新的版本，如果是，则强制退出程序
				if (Integer.valueOf(mUpdateAPKItem.getIs_force()) == UpdateAPKItem.UPDATE_IS_FORCE) {
					ActManager.getAppManager().finishAllActivity();
					android.os.Process.killProcess(android.os.Process.myPid());  
				}
			}
		});
		builder.show();
	}

	@SuppressLint("NewApi")
	private void intoDownloadManager(Activity activity)
	{
		DownloadManager dManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
		Uri uri = Uri.parse(mUpdateAPKItem.getDownload_url());
		Request request = new Request(uri);
		// 设置下载路径和文件名
		request.setDestinationInExternalPublicDir("download", mUpdateAPKItem.getVersion_name()+".apk");
		request.setDescription("德鸿金融新版本下载");
		request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		request.setMimeType("application/vnd.android.package-archive");
		// 设置为可被媒体扫描器找到
		request.allowScanningByMediaScanner();
		// 设置为可见和可管理
		request.setVisibleInDownloadsUi(true);
		long refernece = dManager.enqueue(request);
		// 把当前下载的ID保存起来
		SharedPreferences sPreferences = activity.getSharedPreferences(mActivity.getPackageName(), 0);
		sPreferences.edit().putLong("version", refernece).commit();
	}

	/**
	 * @describe:TODO 获取软件版本号
	 * @param context
	 * @return
	 */
	private int getVersionCode() {
		int versionCode = 0;
		try {
			// 获取软件版本号，
			versionCode = mActivity.getPackageManager().getPackageInfo(
					mActivity.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			LogUtils.e("--------获取版本错误--------", e.getMessage().toString());
		}
		return versionCode;
	}
}
